#!/usr/bin/python
#coding=utf-8

from model.user import User
import MySQLdb
from db_utils import DBUtils 
import utils.log_utils as log 

class UserDB:
    def __init__(self):
        self.dbutils = DBUtils()

    def register(self, user):
        email = MySQLdb.escape_string(user.email)
        passwd = MySQLdb.escape_string(user.passwd)
        params = (email, passwd)
        sql = "insert into user(email, passwd) values(%s, %s)"
        self.dbutils.execute(sql, params)

    def check(self, email):
        email = MySQLdb.escape_string(email)
        sql = "select passwd from user where email = '%s'"
        rows = self.dbutils.execute(sql, email)
        if rows:
            return True
        else:
            return False
               
    def auth(self, user):
        #
        # 如果用户不存在, 返回None.
        # 否则验证用户密码，如果正确返回True,否则返回False.
        #
        email = MySQLdb.escape_string(user.email)
        passwd = MySQLdb.escape_string(user.passwd)
        sql = "select passwd from user where email = %s "
        rows = self.dbutils.execute(sql, email) 
        if rows:  
            passwd = rows[0][0]
            if passwd == user.passwd:
                return True
            else:
                return False
        else:  
            return None 

